<template>
  <!-- 地址界面 -->
  <div>
    <!-- 头部返回 -->
    <van-nav-bar title="收货地址" left-arrow @click-left="exit" />
    <!-- 地址组件 -->
    <van-address-list class="one" v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      chosenAddressId: 2, //默认选中地址
      list: [], //用户已有地址，从数据库中获取
      data: [],
    };
  },
  methods: {
    //新增地址 将本地数据adress清空
    onAdd() {
      this.$router.push({ name: "edit_address", params: { addressId: 0 } });
    },
    //修改地址 传递给修改界面需要修改的地址id
    onEdit(item) {
      this.$router.push({
        name: "edit_address",
        params: { addressId: item.id },
      });
    },
    //返回上一页
    exit() {
      this.$router.go(-1);
    },
    getData() {
      let sta = localStorage.getItem("sta");
      sta = JSON.parse(sta);
      if (sta.sx == 1) {
        let myurl1 = this.$url + "address_read";
        this.axios.post(myurl1, { user_id: sta.id }).then(
          (res1) => {
            this.list=[]
            let b = res1.data.data;
            b = b.replace(/"false"/g, "false");
            b = b.replace(/"true"/g, "true");
            let data_base = JSON.parse(b);
            for (let i = 0; i < data_base.length; i++) {
              let a = {};
              a.id = data_base[i].id;
              a.name = data_base[i].name;
              a.tel = data_base[i].tel;
              a.address =
                data_base[i].province +
                data_base[i].city +
                data_base[i].county +
                data_base[i].addressDetail;
              if (data_base[i].isDefault == true) {
                a.isDefault = true;
                this.chosenAddressId = a.id;
              } else {
                a.isDefault = false;
              }
              this.list.push(a);
            }
            for (let i = 0; i < data_base.length; i++) {
              if (data_base[i].isDefault == true) {
                let address = { sx: 1, id: data_base[i].id };
                address = JSON.stringify(address);
                localStorage.setItem("address", address);
                break;
              } else {
                let address = { sx: 1, id: data_base[i].id };
                address = JSON.stringify(address);
                localStorage.setItem("address", address);
              }
            }
          },
          (err) => {
            console.log("数据读取失败");
            console.log(err);
          }
        );
      }
    },
  },
  created() {
    this.getData();
    //从本地获取登录状态 然后从数据库中读取地址数据 赋值给list
  },
  beforeRouteEnter(to, from, next) {
    // var that = this;
    next((vm) => {
      vm.getData();
    });
  },
};
</script>

<style scoped>
.one{
  height: 80%;
  overflow: scroll;
}
</style>